package com.aliang.jp.jp;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.text.BadLocationException;

import com.aliang.jp.baidu.BaiDuOcrUtil;
import com.aliang.jp.book.Editor;

/**
 * 系统托盘类，初始化系统托盘及相关菜单的响应，另外还提供了几个图片写入的
 * 工个方法，懒得再写其他类了
 * @author liuruile
 */
public class SystemTrayTool {

    private static Settings settings = Settings.getInstance(); // 保存用户的抓屏配置信息
    private Robot robot; // 抓屏机器人
    private Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); // 屏幕大小

    public void initTrayicon() {

        try {
            robot = new Robot(); 
        } catch (AWTException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        // 不支持系统托盘，将弹出配置对话框，用户可以在输入完相关配置信息后
        // 使用配置对话框提供的“开始抓屏”的按钮进行抓屏
        if (!SystemTray.isSupported()) {
//            JDialog dialog = new JDialog();
//            dialog.add(new JLabel("当前系统不支持系统托盘!"));
//            dialog.setLocation(screenSize.width / 2, screenSize.height / 2);
//            dialog.pack();
//            dialog.setVisible(true);
//
//            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            SettingDialog mainDialog = new SettingDialog(new JFrame(), true);
            mainDialog.setLocation((screenSize.width - mainDialog.getWidth()) / 2,
                    (screenSize.height - mainDialog.getHeight()) / 2);
            mainDialog.setVisible(true);
            return;
        }

        PopupMenu menu = new PopupMenu();

        MenuItem xiaoyu = new MenuItem("东高-图片识别");
        xiaoyu.setEnabled(false);
        menu.add(xiaoyu);
        menu.addSeparator();

        MenuItem catchScreen = new MenuItem("截屏识别");
        menu.add(catchScreen);
        catchScreen.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (!ScreenFrame.displayed) {
                    new Thread(new Runnable() {
                        // 为了防止系统托盘的右键菜单不能及时隐去，将屏幕抓取面板
                        // 的初始化放到别处的线程中，避免阻塞事件派发线程
                        public void run() {
                            ScreenFrame.displayed = true;
                            new ScreenFrame(robot, screenSize);
                        }
                    }).start();

                }
            }
        });

        MenuItem configureMenuItem = new MenuItem("配置");
        menu.add(configureMenuItem);
        configureMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SettingDialog dialog = new SettingDialog(new JFrame(), false);
                dialog.setLocation((screenSize.width - dialog.getWidth()) / 2,
                        (screenSize.height - dialog.getHeight()) / 2);
                dialog.setVisible(true);
            }
        });

        MenuItem exit = new MenuItem("退出");
        menu.add(exit);
        exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        SystemTray tray = SystemTray.getSystemTray();
        ImageIcon image = new ImageIcon(SystemTrayTool.class.getResource("/com/aliang/jp/jp/pic/catch.gif"));
        TrayIcon icon = new TrayIcon(image.getImage(), "双击可抓全屏", menu);
        try {
            tray.add(icon);
        } catch (AWTException e) {
            e.printStackTrace();
        }
        icon.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                if (settings.getDelaytime() > 0)
                {
                    try {
                        Thread.sleep(settings.getDelaytime() * 1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(SystemTrayTool.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                Rectangle rct = new Rectangle(0, 0, screenSize.width,
                        screenSize.height);
                BufferedImage im = robot.createScreenCapture(rct);

                outputImage2SavePlace(im, rct);

                writeImageToFile(im, rct);
            }
        });
    }

    /**
     * 将图片的指定区，写入到指定的地方（文件或是剪切板）
     * @param im 抓取到的整个图片
     * @param rct 指定需要保存的图片区域
     */
    public static void outputImage2SavePlace(BufferedImage im, Rectangle rct) {
        if (Settings.getInstance().getSavePlace() == Settings.FILE) {
        	//writeImageToFile(im, rct);
        	  Editor panel = new Editor();
              try {
				panel.textPane.getDocument().insertString(0, BaiDuOcrUtil.ocr(im, rct), null);
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
        } else {
            setImage2Clipboard(im, rct);
        }
    }

    /**
     * 将图片指定区域写入到剪切板
     * @param image
     * @param rct
     */
    private static void setImage2Clipboard(final BufferedImage image, final Rectangle rct) {
        Transferable trans = new Transferable() {

            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            }

            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(flavor);
            }

            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
                if (isDataFlavorSupported(flavor)) {
                    return image.getSubimage(rct.x, rct.y, rct.width, rct.height);
                }
                throw new UnsupportedFlavorException(flavor);
            }
        };
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
    }

    /**
     * 将图片的指定区写入到文件
     * @param im
     * @param rct
     */
    private static void writeImageToFile(BufferedImage im, Rectangle rct) {
        try {
            im = im.getSubimage(rct.x, rct.y, rct.width, rct.height);
            String fileName = settings.getOutputFileName();
            File f = new File(fileName);
            if (!f.exists())
            {
                f.mkdirs();
                if(f.exists())
                {
                    f.createNewFile();
                }
            }
            ImageIO.write(im, settings.getImageFormatString(), f);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
